var express = require('express');
var router = express.Router();
const multiparty = require('multiparty');
const fs = require('fs');
const path = require('path');
const uploadDir = path.join(__dirname, '../upload');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
  console.log('Created upload directory:', uploadDir);
}
//段丽娜
var {
  Material,
  Warehouse,
  StorageLocation,
  Inventory,
  InventoryTransaction,
  PurchaseRequest,
  userModel,
  conversationModel,
  sharedFileModel,
  messageModel,
  callModel,
  PurchaseRequestItem,
  PurchaseOrder,
  PurchaseOrderItem,
  Supplier,
  InboundOrder,
  InboundOrderItem,
} = require('../moduls/storage');
// 获取物料信息列表
router.get('/materials',async (req, res) => {
  try {
    const materials = await Material.find();
    res.json(materials);
  } catch (error) {
    res.status(500).json({ error: '获取物料信息失败' });
  }
})
// 获取入库单明细列表
router.get('/inbound',async (req, res) => {
  try {
    const inboundOrderItems = await InboundOrderItem.find();
    res.json(inboundOrderItems);
  } catch (error) {
    res.status(500).json({ error: '获取入库单明细列表失败' });
  }
})
// 导入axios和dotenv
const axios = require('axios');
require('dotenv').config();

// 百度图像识别接口（新增）
router.post('/baidu-recognize', async (req, res) => {
  try {
    // 从请求体获取图片Base64（前端会传）
    const { imageBase64 } = req.body;
    if (!imageBase64) {
      return res.status(400).json({ error: '未提供有效图片数据' });
    }

    // 1. 获取百度access_token
    const tokenRes = await axios.get(
      `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${process.env.BAIDU_API_KEY}&client_secret=${process.env.BAIDU_SECRET_KEY}`
    );
    const accessToken = tokenRes.data.access_token;

    // 2. 调用百度图像识别接口
    const recognizeRes = await axios.post(
      `https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=${accessToken}`,
      `image=${encodeURIComponent(imageBase64)}`,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    );

    // 返回识别结果给前端
    res.json(recognizeRes.data.result);
  } catch (error) {
    console.error('百度识别接口错误:', error);
    res.status(500).json({ error: '识别失败，请重试' });
  }
});

// 新增：根据关键词查询相关数据接口
router.get('/getrelateddata', async (req, res) => {
  try {
    const { keyword } = req.query
    if (!keyword) {
      return res.status(400).json({ error: '未提供关键词参数' });
    }

    // 示例：假设查询物料表（Material）中名称包含关键词的记录
    const relatedData = await Material.find({ 
      name: { $regex: keyword, $options: 'i' } // 模糊匹配（不区分大小写）
    });

    res.json({
      code: 200,
      data: relatedData,
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询相关数据失败:', error);
    res.status(500).json({ error: '查询相关数据失败' });
  }
});

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


//获取用户列表
router.get('/userlist', async (req, res) => {
  const senderId = req.query.senderId
  if (!senderId) {
    return res.status(400).send({ code: 400, msg: '缺少 senderId' });
  }
  let users = await userModel.find({ _id: { $ne: senderId } }).lean()
  const conversations = await conversationModel.find({ participants: senderId }).populate('lastMessage').sort({ updatedAt: -1 }).lean()
  const data = users.map(user => {
    const conv = conversations.find(c => c.participants.some(p => p.toString() == user._id.toString()))
    const unread = conv?.unreadCounts.find(uc => uc.user == senderId)?.count || 0
    return {
      _id: user._id,
      name: user.name,
      avatar: user.avatar,
      online: user.online,
      lastMessage: conv?.lastMessage?.content || '',
      unread
    }
  })
  res.send({
    code: 200,
    data
  })
})
//添加用户
router.post('/userlist', (req, res) => {
  userModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})
//添加消息
router.post('/message', async (req, res) => {
  const isFileUpload = req.headers['content-type']?.includes('multipart/form-data');
  if (isFileUpload) {
    const form = new multiparty.Form({
      uploadDir,
      maxFilesSize: 10 * 1024 * 1024,
    });
    form.parse(req, async (err, fields, files) => {
      if (err) {
        console.error('文件解析错误:', err, { code: err.code, path: err.path });
        return res.status(500).send({ code: 500, msg: `文件解析失败: ${err.message}` });
      }
      console.log('收到文件上传请求:', fields, files);
      const senderId = fields.senderId?.[0];
      const receiverId = fields.receiverId?.[0];
      const content = fields.content?.[0];
      const type = fields.type?.[0];
      if (!senderId || !receiverId || !type) {
        console.error('缺少必要字段:', { senderId, receiverId, type });
        return res.status(400).send({ code: 400, msg: '缺少必要字段: senderId, receiverId 或 type' });
      }
      await handleMessage({ senderId, receiverId, content, type, files, res });
    });
  } else {
    const { senderId, receiverId, content, type = 'text', file } = req.body;
    if (!senderId || !receiverId) {
      console.error('缺少必要字段:', { senderId, receiverId });
      return res.status(400).send({ code: 400, msg: '缺少必要字段: senderId 或 receiverId' });
    }
    await handleMessage({ senderId, receiverId, content, type, file, res });
  }
});

async function handleMessage({ senderId, receiverId, content, type, files, file, res }) {
  try {
    if (!senderId || !receiverId) {
      return res.status(400).send({ code: 400, msg: '缺少 senderId 或 receiverId' });
    }
    const sender = await userModel.findOne({ _id: senderId });
    const receiver = await userModel.findOne({ _id: receiverId });
    if (!sender || !receiver) {
      return res.status(400).send({ code: 400, msg: '用户不存在' });
    }
    if (!receiver.online) {
      return res.status(400).send({ code: 400, msg: '接收者不在线' });
    }
    let conversation = await conversationModel.findOne({
      participants: { $all: [senderId, receiverId] },
    });
    if (!conversation) {
      conversation = await conversationModel.create({
        participants: [senderId, receiverId],
        createdAt: Date.now(),
      });
    }
    let fileData;
    if (['image', 'video', 'audio', 'file'].includes(type) && files?.file?.[0]) {
      const uploadedFile = files.file[0];
      const fileTypes = {
        image: /jpeg|jpg|png|gif|webp/,
        video: /mp4|webm/,
        audio: /mp3|wav/,
        file: /.*/i,
      };
      const extname = fileTypes[type].test(path.extname(uploadedFile.originalFilename).toLowerCase());
      const mimeType = fileTypes[type].test(uploadedFile.headers['content-type']);
      if (!extname || !mimeType) {
        fs.unlinkSync(uploadedFile.path);
        return res.status(400).send({ code: 400, msg: '文件类型不支持' });
      }
      const newFileName = `${Date.now()}-${uploadedFile.originalFilename}`;
      const newPath = path.join(uploadDir, newFileName);
      console.log('保存文件到:', newPath);
      try {
        await fs.promises.rename(uploadedFile.path, newPath);
      } catch (renameErr) {
        console.error('文件重命名失败:', renameErr);
        return res.status(500).send({ code: 500, msg: `文件保存失败: ${renameErr.message}` });
      }
      fileData = {
        url: `/upload/${newFileName}`,
        name: uploadedFile.originalFilename,
        size: (uploadedFile.size / 1024 / 1024).toFixed(2) + 'MB',
        mimeType: uploadedFile.headers['content-type'],
      };
      await sharedFileModel.create({
        conversation: conversation._id,
        uploader: senderId,
        type,
        url: fileData.url,
        name: fileData.name,
        size: fileData.size,
        mimeType: fileData.mimeType,
        uploadedAt: Date.now(),
      });
    }
    const messageData = {
      conversation: conversation._id,
      sender: senderId,
      receiver: receiverId,
      content: fileData ? fileData.url : content,
      type,
      timestamp: Date.now(),
    };
    const message = await messageModel.create(messageData);
    res.send({ code: 200, data: message });
  } catch (err) {
    console.error('处理消息失败:', err);
    res.status(500).send({ code: 500, msg: '处理消息失败' });
  }
}
//获取消息
router.get('/message', async (req, res) => {
  let { sender, receiver } = req.query
  let conversation = await conversationModel.findOne({ participants: { $all: [sender, receiver] } })
  if (!conversation) {
    res.send({
      code: 200,
      data: []
    })
  } else {
    let message = await messageModel.find({ conversation: conversation._id }).populate('sender', 'name avatar').sort({ time: 1 }).lean()
    res.send({
      code: 200,
      data: message,
    })
  }
})
//处理通话
router.post('/call', async (req, res) => {
  const { senderId, receiverId, type, status, duration } = req.body;
  console.log(`收到通话请求: senderId=${senderId}, receiverId=${receiverId}, type=${type}, status=${status}, duration=${duration || 'N/A'}`);

  // 验证接收者
  const receiver = await userModel.findOne({ _id: receiverId });
  if (!receiver || !receiver.online) {
    return res.send({ code: 400, msg: '接收者不在线' });
  }

  // 查找或创建会话
  let conversation = await conversationModel.findOne({
    participants: { $all: [senderId, receiverId] },
  }) || await conversationModel.create({
    participants: [senderId, receiverId],
    createdAt: Date.now(),
    unreadCounts: [{ user: senderId, count: 0 }, { user: receiverId, count: 0 }],
  });

  // 创建通话记录
  let callData = {
    conversation: conversation._id,
    initiator: senderId,
    participants: [senderId, receiverId],
    type,
    status,
    startTime: status === 'connected' ? Date.now() : undefined,
    endTime: status === 'ended' ? Date.now() : undefined,
    duration: duration || 0, // 使用客户端提供的时长
  };

  const call = await callModel.create(callData);

  // 仅在 ended, missed, declined 状态生成消息
  if (['ended', 'missed', 'declined'].includes(status)) {
    const content = {
      ended: `${type === 'audio' ? '语音' : '视频'}通话已结束${duration ? `，时长：${Math.round(duration)}秒` : ''}`,
      missed: `${type === 'audio' ? '语音' : '视频'}通话未接通`,
      declined: `${type === 'audio' ? '语音' : '视频'}通话已取消`,
    }[status];

    const messageData = {
      conversation: conversation._id,
      sender: senderId,
      receiver: receiverId,
      content,
      type: 'call',
      timestamp: Date.now(),
      isRead: false,
    };

    const message = await messageModel.create(messageData);
    await conversationModel.updateOne(
      { _id: conversation._id },
      {
        lastMessage: message._id,
        $inc: { 'unreadCounts.$[elem].count': senderId === receiverId ? 0 : 1 },
      },
      { arrayFilters: [{ 'elem.user': receiverId }] }
    );
  }

  res.send({ code: 200, data: call });
});
router.put('/message/read', async (req, res) => {
  const { senderId, receiverId } = req.body
  try {
    const conversation = await conversationModel.findOne({
      participants: { $all: [senderId, receiverId] }
    })
    if (!conversation) {
      res.send({
        code: 400,
        msg: '对话不存在'
      })
    }
    await messageModel.updateMany({
      conversation: conversation._id,
      isRead: false,
      sender: receiverId
    }, { isRead: true })
    await conversationModel.updateOne({ _id: conversation._id },
      { $set: { 'unreadCounts.$[elem].count': 0 } },
      { arrayFilters: [{ 'elem.user': senderId }] })
    res.send({
      code: 200,
      msg: '已阅'
    })
  } catch (err) {
    res.send({
      code: 500,
      msg: err.message
    })
  }
})
router.get('/sharedFiles', async (req, res) => {
  
  try {

    const {  type,conversationId } = req.query;    // 按文件类型过滤
let arr=[]
if(type!=="all"){
  arr.push({ type: type })
}
arr.push({ conversation: conversationId })
    const files = await sharedFileModel
      .find({$and:arr})
      .populate('conversation', 'participants')
      .populate('uploader', 'name')
      .sort({ uploadedAt: -1 });

    res.send({
      code: 200,
      data: files.map(file => ({
        _id: file._id,
        name: file.name,
        type: file.type,
        size: file.size,
        url: file.url,
        uploader: file.uploader?.name || '未知用户',
        time: new Date(file.uploadedAt).toLocaleString(),
      })),
    });
  } catch (err) {
    console.error('获取共享文件失败:', err);
    res.status(500).send({
      code: 500,
      msg: '获取共享文件失败',
    });
  }
});
router.get('/conversation', async (req, res) => {
  try {
    const { senderId, receiverId } = req.query;
    if (!senderId || !receiverId) {
      return res.status(400).send({
        code: 400,
        msg: '缺少 senderId 或 receiverId 参数',
      });
    }

    let conversation = await conversationModel.findOne({
      participants: { $all: [senderId, receiverId] },
    });

    if (!conversation) {
      conversation = await conversationModel.create({
        participants: [senderId, receiverId],
        createdAt: Date.now(),
        unreadCounts: [
          { user: senderId, count: 0 },
          { user: receiverId, count: 0 },
        ],
      });
      console.log('创建新会话:', conversation._id);
    }

    res.send({
      code: 200,
      data: {
        _id: conversation._id,
        participants: conversation.participants,
        createdAt: conversation.createdAt,
        unreadCounts: conversation.unreadCounts,
        lastMessage: conversation.lastMessage,
      },
    });
  } catch (err) {
    console.error('获取会话失败:', err);
    res.status(500).send({
      code: 500,
      msg: '获取会话失败',
    });
  }
});
router.get('/call/status', async (req, res) => {
  const { senderId, receiverId, type } = req.query;
  try {
    const call = await callModel.findOne({
      $or: [
        { initiator: senderId, participants: { $all: [senderId, receiverId] }, type },
        { initiator: receiverId, participants: { $all: [senderId, receiverId] }, type }
      ],
      status: { $in: ['initiated', 'connected'] }
    }).sort({ createdAt: -1 });

    if (call) {
      res.json({ code: 200, data: { status: call.status } });
    } else {
      res.json({ code: 404, msg: '未找到通话记录' });
    }
  } catch (err) {
    console.error('获取通话状态失败:', err);
    res.status(500).json({ code: 500, msg: '服务器错误' });
  }
});
 router.get('/logguan',async(req,res)=>{
  let {page,pageSize,type,code,name,isActive}=req.query
  let arr=[]
  if(type){
    arr.push({type})
  }
  if(code){
    arr.push({code:{$regex:code}})
  }
  if(name){
    arr.push({name:{$regex:name}})
  }
  if(isActive){
    arr.push({isActive:{$regex:isActive}})
  }
  const list=await Material.find({$and:arr}).skip((page-1)*pageSize).limit(pageSize)
  const total=await Material.countDocuments({$and:arr})
  res.send({
    code:200,
    list,
    total
  })
 })
router.get('/info',async(req,res)=>{
  let {_id}=req.query
  const info=await Material.findOne(_id)
  res.send({
    code:200,
    info
  })
})
// 在后端添加导入接口
router.post('/logguan/import', async (req, res) => {
  try {
    const importData = req.body; // 接收前端传来的数据数组
    
    // 批量插入数据到数据库
    const result = await Material.insertMany(importData);
    
    res.send({
      code: 200,
      message: '导入成功',
      data: result
    });
  } catch (error) {
    console.error('导入失败:', error);
    res.status(500).send({
      code: 500,
      message: '导入失败',
      error: error.message
    });
  }
});
router.post('/logguan/add',async(req,res)=>{
  await Material.create(req.body)
  console.log(req.body);
  res.send({
    code:200,
    message:'修改成功'
   
  })
})
// router.post('/logguan/add',async(req,res)=>{
//   let {user}=req.body
//   console.log(user);
//   const info=await Material.findOne(user.code)
//   if(info){
//     res.send({
//       code:500,
//       message:'物料编码重复'
//     })
//   }else{
//     await Material.create({user})
//   }
//   res.send({
//     code:200,
//     message:'添加成功'
//   })
// })
router.post('/upload',async(req,res)=>{
let form=new multiparty.Form()
form.uploadDir='upload'
form.parse(req,(err,a,b)=>{
res.send({
path:'http://localhost:3000/'+b.file[0].path
})
})
})
// 根据条形码（批次号）更新入库明细状态
router.post('/inbound/updatestatus', async (req, res) => {
  try {
    const { batchNumber, newStatus } = req.body;
    
    // 验证参数是否存在
    if (!batchNumber || !newStatus) {
      return res.status(400).json({ error: '缺少必要参数：batchNumber（批次号）或newStatus（新状态）' });
    }

    // 验证新状态是否合法（需与inboundOrderItemSchema中的enum一致）
    const validStatuses = ['pending', 'inspected', 'stored'];
    if (!validStatuses.includes(newStatus)) {
      return res.status(400).json({ error: '无效的状态值，允许的值：pending/inspected/stored' });
    }

    // 根据批次号查找入库明细
    const inboundItem = await InboundOrderItem.findOne({ batchNumber });
    if (!inboundItem) {
      return res.status(404).json({ error: '未找到对应批次号的入库记录' });
    }

    // 更新状态并保存
    inboundItem.status = newStatus;
    await inboundItem.save();

    res.json({ success: true, message: '入库状态更新成功', data: inboundItem });
  } catch (error) {
    console.error('更新入库状态失败:', error);
    res.status(500).json({ error: '服务器错误，更新状态失败' });
  }
});


module.exports = router;

